package com.liangtian.mdm.dm.jsp.service.imp;

import com.liangtian.mdm.base.dao.JdbcDao;
import com.liangtian.mdm.base.utils.ShiroSessionUtils;
import com.liangtian.mdm.dm.common.constant.TableConst;
import com.liangtian.mdm.dm.common.enums.Flag;
import org.apache.commons.lang3.StringUtils;
import com.liangtian.mdm.dm.config.dao.AttrConfigDao;
import com.liangtian.mdm.dm.config.model.AttrConfig;
import com.liangtian.mdm.dm.jsp.common.JspUtil;
import com.liangtian.mdm.dm.jsp.service.JspExpImpService;
import com.liangtian.mdm.dm.jsp.util.ExcelExpUtil;
import com.liangtian.mdm.dm.jsp.util.ExcelImpUtil;
import com.liangtian.mdm.dm.listener.CacheUtil;
import com.liangtian.mdm.dm.model.model.Model;
import com.liangtian.mdm.util.StringUtil;
import com.liangtian.mdm.system.user.model.SysUser;
import com.liangtian.mdm.util.ConstantBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings({"rawtypes", "unchecked"})
@Service
public class JspExpImpServiceImpl implements JspExpImpService {
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private AttrConfigDao attrConfigDao;
    @Autowired
    private ExcelExpUtil excelExpUtil;
    @Autowired
    private ExcelImpUtil excelImpUtil;
    @Autowired
    private JdbcDao jdbcDao;

    @Override
    public String ExportModelExcelInfo(String modelId, HttpServletResponse response) {
        Model model = cacheUtil.getModel(modelId);
        String error = "";
        try {
            //获取当前主数据的属性列表
            List<AttrConfig> configLst = getAttrcList(model, modelId);
            //判断当前主数据是否有从表,如果有从表,获取所有从表名称(用来生成对应的sheet页的名称)以及从表的属性列表
            Map<String, List<AttrConfig>> map = getMainTableAttrConfig(modelId);
            excelExpUtil.exportExcelTemp(model, configLst, map, response);
        } catch (Exception e) {
            error = e.getMessage();
            e.printStackTrace();
        }
        return null;
    }

    //判断当前主数据是否有从表,如果有从表,将从表的信息查询出来,以Map<从表名称,List<从表属性>>的格式返回
    private Map<String, List<AttrConfig>> getMainTableAttrConfig(String modelId) {
        //当前sql用来判断当前主数据是否有从表
        String sonSql = "select id||',,,'||model_name from am_model where is_subtable = 1 and maintable_id = '" + modelId + "'";
        List<String> sonList = jdbcDao.executeSqlSelectId(sonSql);
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        Map<String, List<AttrConfig>> mapRes = new HashMap<String, List<AttrConfig>>();
        List<AttrConfig> configSonLst = new ArrayList<AttrConfig>();
        for (String str : sonList) {
            Map<String, String> mapCon = new HashMap<String, String>();
            String[] strArr = str.split(",,,");
            mapCon.put("tableTable", TableConst.TABLEPREFIX + strArr[0]);
            mapCon.put("userId", user.getUserId() + "");
            configSonLst = attrConfigDao.queryAttributesListPermision(mapCon);
            mapRes.put(str, configSonLst);
        }
        return mapRes;
    }

    //获取当前主数据的属性列表---导出模板时候的表头信息
    private List<AttrConfig> getAttrcList(Model model, String modelId) throws Exception {

        List<AttrConfig> configLst = null;
        Map<String, String> map = new HashMap<String, String>();
        try {
            SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
            map.put("tableTable", TableConst.TABLEPREFIX + modelId);
            map.put("userId", user.getUserId() + "");

            if (model.getIsMoreView() == 1) {//表示是多视图
                configLst = attrConfigDao.queryMoreViewAttrForExport(modelId);
            } else {
                configLst = attrConfigDao.queryAttributesListPermision(map);    //根据modelid 和登录用户id查询当前用户拥有的属性权限
            }
        } catch (Exception e) {
            throw new Exception("获取当前主数据的属性列表失败," + e.getMessage());
        }
        return configLst;
    }

    @Override
    public String importModelExcelInfo(String modelId, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Model model = cacheUtil.getModel(modelId);
        String fileName = "";
//		try {
        //获取当前主数据的属性列表
        List<AttrConfig> configLst = getAttrcList(model, modelId);
        //判断当前主数据是否有从表,如果有从表,获取所有从表名称(用来生成对应的sheet页的名称)以及从表的属性列表
        Map<String, List<AttrConfig>> map = getMainTableAttrConfig(modelId);
//			excelExpUtil.exportExcelTemp(model,configLst,map,response);
        Map<String, Object> retMap = excelImpUtil.excelImport(configLst, map, response, request);
        fileName = (String) retMap.get("fileName");
        if (StringUtils.isEmpty(fileName)) {
            List<Map<String, String>> dataList = (List<Map<String, String>>) retMap.get("dataLst");
            insertIntoDataBase(modelId, dataList);
        }
//		} catch (Exception e) {
//			e.printStackTrace();
//		} 
        return fileName;
    }

    private void insertIntoDataBase(String modelId, List<Map<String, String>> dataList) {
        //表名
        String tableName = "T_" + modelId;
        StringBuffer headStr = new StringBuffer();
        StringBuffer valStr = new StringBuffer();
        headStr.append("insert into ").append(tableName).append("(");
        SysUser user = ShiroSessionUtils.getSessionSysUser(ConstantBean.CURRENT_SESSION_USER);
        for (int i = 0; i < dataList.size(); i++) {
            for (Map.Entry<String, String> entry : dataList.get(i).entrySet()) {
                System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
                if (0 == i) {
                    headStr.append(entry.getKey() + ",");
                }
                String value = entry.getValue();
                if (null != value) {
                    if (value.startsWith("{") && value.endsWith("}")) {
                        value = JspUtil.formatSelectCol(value);
                    }
                    value = StringUtil.escapeSql(value);
                    valStr.append("'").append(value).append("',");
                } else {
                    valStr.append(" null,");
                }

            }
            valStr.append("get_seq('" + tableName).append(TableConst.SEQUENCESUFFIX).append("'), '");
            valStr.append(user.getUserId().longValue()).append("', '");
            valStr.append(user.getUserName()).append("', sysdate,  0, ");
            valStr.append(Flag.STATE_0.getCode()).append(", ");
            valStr.append(Flag.STATUS_0.getCode()).append(", ");        // 数据状态
            valStr.append(Flag.DISPATCH_0.getCode()).append(", ");
            valStr.append(StringUtil.safeNull("")).append(", ");
            valStr.append(StringUtil.safeNull(""));
            valStr.append(" from dual ");
            if (i != dataList.size() - 1) {
                valStr.append(" union select ");
            }
        }

        headStr.append("id, creater_id, creater_name, creater_time, version, state, status, dis_flag, pid, mainid)");
        String sql = headStr.append("select ").append(valStr).toString();
        System.out.println(headStr.append("select ").append(valStr));
        jdbcDao.executeSql(sql);
    }

}
